package testappserver;

import guiclient.Application;
import guicommon.controls.*;
import guicommon.controls.handlers.MouseClickedEventHandler;
import guicommon.controls.handlers.MouseEventArgs;
import java.awt.Color;
import java.io.IOException;
import java.util.Random;

public class ServerGUI extends Application {

    private Window window;
    private Button button;
    private Label realNumberLabel;
    private Label intNumberLabel;
    private TextBox tbLastNumber;
    private TextBox tbLastClient;
    private Random random;

    ServerGUI() throws IOException {
        random = new Random(System.currentTimeMillis());

        window = new Window();
        window.SetSize(200, 150);
        window.SetPoint(50, 10);
        window.SetTitle("Server");
        window.SetBackGround(Color.lightGray);
        RegisterControl(window);

        realNumberLabel = new Label();
        realNumberLabel.SetSize(50, 20);
        realNumberLabel.SetPoint(15, 30);
        realNumberLabel.SetOwner(window);
        realNumberLabel.SetText("Num:");
        realNumberLabel.SetBackGround(Color.lightGray);
        RegisterControl(realNumberLabel);

        intNumberLabel = new Label();
        intNumberLabel.SetSize(50, 20);
        intNumberLabel.SetPoint(15, 60);
        intNumberLabel.SetOwner(window);
        intNumberLabel.SetText("Client:");
        intNumberLabel.SetBackGround(Color.lightGray);
        RegisterControl(intNumberLabel);

        tbLastNumber = new TextBox();
        tbLastNumber.SetSize(100, 20);
        tbLastNumber.SetPoint(75, 30);
        tbLastNumber.SetOwner(window);
        tbLastNumber.SetText("0");
        tbLastNumber.SetBackGround(Color.white);
        RegisterControl(tbLastNumber);

        tbLastClient = new TextBox();
        tbLastClient.SetSize(100, 20);
        tbLastClient.SetPoint(75, 60);
        tbLastClient.SetOwner(window);
        tbLastClient.SetText("0");
        tbLastClient.SetBackGround(Color.white);
        RegisterControl(tbLastClient);

        button = new Button();
        button.SetSize(70, 20);
        button.SetPoint(65, 90);
        button.SetOwner(window);
        button.SetBackGround(Color.gray);
        button.SetText("Update");
        button.SetMouseClickedEventHandler(new MouseClickedEventHandler() {

            @Override
            public void Event(Control sender, MouseEventArgs args) {
                int rand = random.nextInt(4);
                if (rand == 0) {
                    Main.Stop();
                } else {
                    double newNumber = random.nextDouble();
                    String num = String.valueOf(newNumber);
                    tbLastNumber.SetText(num.substring(0, Math.min(num.length() - 1, 6)));
                    tbLastClient.SetText(String.valueOf(rand));
                    Main.SendMessage(rand, newNumber);
                }
            }
        });
        RegisterControl(button);        
    }
}
